<?php

class PermissionController extends St_Controller_Action_Admin {

    public function init() {
        parent::init();
    }

    public function indexAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }

        $filter = $this->session->PermissionType;

        if (isset($_POST['filter'])) {
            $this->session->PermissionType = $filter = $_POST['filter'];
        }

        Zend_Loader::loadClass("St_Permission");
        $permissionObj = new St_Permission ();
        $datas = $permissionObj->fetchAll();
        $this->view->datas = $datas;
        $this->view->baselink = St_Registry::getConfig("base_url");
        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('p' => 'permission'))
                ->order("PermissionType ASC")
        ;
        if ($filter) {
            if ($filter['PermissionType'] != "*")
                $select->where($permissionObj->getAdapter()->quoteInto("PermissionType = ?", $filter['PermissionType']));
        }

        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        $db = St_Registry::getDB();
        $config = St_Registry::getConfig('display');                
        $paginator->setItemCountPerPage ( $config['numberPerPage'] );                
        $paginator->setPageRange ( $config['pageRange'] );
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);
        $this->view->PermissionTypeList = $PermissionTypeList = $db->fetchAll("SELECT DISTINCT PermissionType from permission");
        $this->view->filter = $filter;
    }

    public function grantAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }

        $filter = $this->session->groupPermissionFilter;

        if (isset($_POST['filter'])) {
            $this->session->groupPermissionFilter = $filter = $_POST['filter'];
        }
        $this->view->baselink = St_Registry::getConfig("base_url");
        $groupPermissionList = $this->_getPermissionData("group");
        if (!$filter || !isset($filter['GroupID'])) {

            $filter = array('GroupID' => $groupPermissionList['siteuser_group_id']);
        }

        $typeFilter = $this->session->PermissionType;

        if (isset($_POST['filter'])) {
            $this->session->PermissionType = $typeFilter = $_POST['filter'];
        }

        Zend_Loader::loadClass("St_Permission");
        $permissionObj = new St_Permission ();
        $datas = $permissionObj->fetchAll();
        $this->view->datas = $datas;

        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();

        $groupSelect = $db->select()->from(array('gp' => "group_permission"));

        if ($filter) {
            if ($filter['GroupID']) {
                $groupSelect->where($permissionObj->getAdapter()->quoteInto("gp.GroupID = ?", $filter['GroupID']));
            }
        }

        $select = $db->select()
                ->from(array('p' => 'permission'))
                ->joinLeft(array('s' => $groupSelect), 'p.PermissionID = s.PermissionID', array('GroupID' => 'GroupID'))
                ->order("PermissionType ASC");

        if (isset($filter['PermissionType'])) {
            if ($filter['PermissionType'] != "*")
                $select->where($permissionObj->getAdapter()->quoteInto("p.PermissionType = ?", $filter['PermissionType']));
        }

        //echo "<pre>";print_r($db->fetchAll($select));die;
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        $db = St_Registry::getDB();
        $config = St_Registry::getConfig('display');                
        $paginator->setItemCountPerPage ( $config['numberPerPage'] );                
        $paginator->setPageRange ( $config['pageRange'] );
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);

        $this->view->filter = $filter;
        $this->view->typeFilter = $typeFilter;
        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll("GroupID <> '{$groupPermissionList['superadmin_group_id']}'")->toArray();
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;
        $this->view->PermissionTypeList = $PermissionTypeList = $db->fetchAll("SELECT DISTINCT PermissionType from permission");
    }

    public function refreshAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }
        Zend_Loader::loadClass("St_Permission");
        $permissionObj = new St_Permission ();

        $currentPermissionList = $this->_getPermissionData("list");

        foreach ($currentPermissionList as $key => $value) {
            if (!$permissionObj->getByKey($key)) {
                $data = array();
                $data['PermissionKey'] = $key;
                $data['Name'] = $value['name'];
                $data['Description'] = $value['description'];
                $data['PermissionType'] = $value['type'];
                $permissionObj->insert($data);
            }
        }
        $currentControllerName = St_Registry::getControllerName();
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function deleteAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }

        $pid = $this->_getParam("pid", false);
        if (!$pid) {
            $this->_redirect("permission");
        }
        Zend_Loader::loadClass("St_Permission");
        $permissionObj = new St_Permission ();
        $permissionObj->delete("PermissionID = '{$pid}'");

        $db = St_Registry::getDB();
        $db->delete("group_permission", "PermissionID = '{$pid}'");
        $user = $this->_getCurrentUser();
        $this->logger->log($user['UserName'] . " deletes PermissionID =" . $pid);
        $currentControllerName = St_Registry::getControllerName();
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function activeAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }

        $gid = $this->_getParam("gid", false);
        $pid = $this->_getParam("pid", false);
        $doAction = $this->_getParam("do", false);

        if (!$gid || !$pid || !$doAction) {
            $this->_redirect("permission/grant");
        }

        Zend_Loader::loadClass("St_Permission");
        $permissionObj = new St_Permission ();

        $currentControllerName = St_Registry::getControllerName();
        $db = St_Registry::getDB();
        if ($doAction == 'insert') {
            $db->insert("group_permission", array('GroupID' => $gid, 'PermissionID' => $pid));
            $user = $this->_getCurrentUser();
            $this->logger->log($user['UserName'] . " adds the relation of GroupID=" . $gid . " and PermissionID=" . $pid);
        } else {
            $db->delete("group_permission", "GroupID = '{$gid}' AND PermissionID = '{$pid}'");
            $user = $this->_getCurrentUser();
            $this->logger->log($user['UserName'] . " deletes the relation of GroupID=" . $gid . " and PermissionID=" . $pid);
        }
        //redirect to other action
        $this->_redirect("{$currentControllerName}/grant/page/{$this->_getParam("page", 1)}");
    }

    public function editAction() {
        if (!$this->acl->isAllow(array("access_permission_system"))) {
            $this->_forward("deny", "access");
            return;
        }

        $canAdd = true;
        $result = false;
        $uid = $this->_getParam("uid", false);
        if (!$uid) {
            $this->_redirect("user");
        }

        $this->view->dataId = $uid;
        Zend_Loader::loadClass("St_User");
        $siteObj = new St_User();

        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'st_user'))
                ->joinLeft(array('g' => 'st_group'), 'g.GroupID = u.GroupID', array('GroupName' => 'GroupName'))
                ->where("UserID = '$uid'");
        $arrayRow = $db->fetchRow($select);

        if ($arrayRow) {
            $this->view->data = $arrayRow;
        }

        $data = $this->_getParam("data", false);
        if ($data) {

            if ($data['UserName'] == "") {
                $canAdd = false;
            }

            if (($data['Password'] != "" || $data['RetypePassword'] != "") && ($data['Password'] != $data['RetypePassword'])) {
                $canAdd = false;
            }

            if ($data['Password'] != "") {
                unset($data['RetypePassword']);
                $data['Password'] = md5($data['Password']);
            } else {
                unset($data['RetypePassword']);
                unset($data['Password']);
            }

            if ($canAdd) {
                $data['LastUpdated'] = time();
                $result = $siteObj->update($data, "UserID = '$uid'");
            }

            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " edits UserID=" . $uid);
                $this->view->msg = "Update user successfully";
            } else {
                $this->view->msg = "Can't update user";
            }
            $this->view->data = $data;
        }

        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll()->toArray();
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;
    }

}

